import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import com.st.utils.DataList
import grails.converters.JSON

// TODO: modify to allow user also.
@Secured(['ROLE_ADMIN', 'ROLE_POWER_USER'])
class NotificationController extends AbstractSecurity {

    static sdf = new java.text.SimpleDateFormat("MM/dd/yyyy hh:mm")

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def emailerService
    def personService
    
    /** VIEWS **/
    // List Views
    def index = {
        redirect(action:list,params:params)
    }

    def list = {
        println "in list notifications " + params
        if (params.companyId) {
            def company = Company.get(params.companyId)
            if (company) {
                return [company:company]
            }
        }
    }

    // Show Views
    def show = {
        def notification = Notification.get(params.id)

        if(!notification) {
            flash.message = "Notification not found with id ${params.id}"
            redirect(action:list)
        } else { 
            return [notification:notification]
        }
    }

    // Create/Edit Views
    def create = {
        if (!params.companyId) {
            redirect action:list
            return
        }

        def notification = new Notification()
        def company = Company.get(params.companyId)
        if (!company) {
            redirect action:list
            return
        }

        def defaultRepId = 0
        def defaultRep = personService.getRepForCurrentUser(Representative.SALES)
        if (company.reps?.size() == 0 || company.reps?.contains(defaultRep)) {
            defaultRepId = defaultRep.id
        }

        notification.properties = params
        return [notification:notification, company:company, defaultRepId:defaultRepId, returnTo:params.returnTo]
    }

    def edit = {
        def notification = Notification.get(params.id)

        if(!notification) {
            flash.message = "Notification not found with id ${params.id}"
            redirect(action:list)
        } else {
            return [notification:notification]
        }
    }

    /** ACTIONS **/
    // Save/Update/Delete Actions
    def complete = {
        params.complete = true
        update()
    }

    def delete = {
        def notification = Notification.get(params.id)
        if(notification) {
            try {
                notification.delete(flush:true)
                flash.message = "Notification ${params.id} deleted"
                redirect(action:list)
            } catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Notification ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Notification not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def notifyNow = {
        def notification = Notification.get(params.id)
        if (notification) {
            def rep = Representative.get(notification.rep.id)
            if (rep?.person.email) {
                println sendMail {
                    to "${rep.person.email}"
                    from "${grailsApplication.config.notifications.from.address}"
                    subject "${notification.type?:""} ${notification.company?:""} TDCMW Notification"
                    body """
Company: ${notification.company}
Contact: ${notification.contact?:"None Listed"}
Type: ${notification.type?:"None Listed"}

Reason: ${notification.reason}

${notification.notes?"Notes: " + notification.notes:""}
                    """
                }
            }
        }
        redirect action:params.returnAction, id:notification.id
    }

    def save = {
        println "save notification " + params
        def notification = new Notification(params)
        if(!notification.hasErrors() && notification.save()) {
            flash.message = "Notification ${notification.id} created"
            if (params.returnToCompany) {
                redirect controller:'company', action:'edit', id:params.company.id
            } else {
                redirect action:show, id:notification.id
            }
        }
        else {
            render view:'create', model:[notification:notification, companyId:params.company.id]
        }
    }

    def update = {
        def notification = Notification.get(params.id)
        if (notification) {
            if (params.version) {
                def version = params.version.toLong()
                if (notification.version > version) {
                    notification.errors.rejectValue("version", "notification.optimistic.locking.failure", "Another user has updated this Notification while you were editing.")
                    render(view:'edit',model:[notification:notification])
                    return
                }
            }
            notification.properties = params
            if (!notification.hasErrors() && notification.save()) {
                flash.message = "Notification ${params.id} updated"
                redirect(action:show,id:notification.id)
            } else {
                render(view:'edit',model:[notification:notification])
            }
        } else {
            flash.message = "Notification not found with id ${params.id}"
            redirect(action:list)
        }
    }

    /** JSON DATA **/
    def listAsJSON = {
        println "list notifications as json " + params
        def notifications
        if (params.companyId != "null") {
            notifications = Notification.findAllByCompany(Company.get(params.companyId))
        } else {
            notifications = Notification.list(max:params.max, offset:params.offset)
        }
        notifications = notifications.collect {[
            id:it.id,
            dataUrl:g.createLink(controller:'notification', action:'show') + "/$it.id",
            date:sdf.format(it.date),
            complete:it.complete?'Yes':'No',
            rep:it.rep.person.name,
            contact:it.contact?.name?:"",
            reason:it.reason
        ]}
        notifications.sort {first, second ->
            def left
            def right
            if (params.order == 'desc') {
                left = second
                right = first
            } else {
                left = first
                right = second
            }
            left."$params.sort" <=> right."$params.sort"
        }
        render DataList.createListWithSize(notifications.size(), notifications) as JSON
    }
}
